#include "netPack.h"
#include "PackDefine.h"

//PackInfo
PackInfo::PackInfo()
{	
	addr = 0x1;
	head2 = 0xaa;
	cmd = 0;
	len = 0;
}

int PackInfo::headLength() const
{
	return 5;
}

int PackInfo::bodyLength() const
{
	return len;
}

bool PackInfo::Pack(QByteArray &buffer) const
{
	QDataStream out(&buffer, QIODevice::WriteOnly);
	out.setByteOrder(QDataStream::LittleEndian);
	
	out << addr;
	out << head2;
	out << cmd;
	out << len;

	return true;
}

bool PackInfo::UnPack(QByteArray &buffer,int offset)
{		
	int head_len = headLength();
	int tail_len = 3;
	if (offset + head_len + tail_len > buffer.size())
		return false;

	uchar *ptr = (uchar *)buffer.data();	
	addr = *((ushort*)(ptr + offset + 0));
	head2 = (uchar)buffer[offset + 2];
	cmd = (uchar)buffer[offset + 3];
	len = (uchar)buffer[offset + 4]; 
	
	int body_len = len;
	if (offset + head_len + body_len + tail_len > buffer.size())
		return false;

	return true;
}

//
NetPack::NetPack()	
{		
	
}

NetPack::~NetPack()
{
}


//NetPackManager
NetPackManager::NetPackManager()
{
	mPackSeq = 1;
}

NetPackManager *NetPackManager::instance()
{
	static NetPackManager inst;
	return &inst;
}

int NetPackManager::genSeq()
{
	return mPackSeq++;
}

NetPack *NetPackManager::createPack(int id)
{
	if (mPackFactory.contains(id))
		return mPackFactory[id]();

	Q_ASSERT(0);
	return NULL;
}